
import { Button, ButtonProps } from "@/components/base";
import ICapability from "../interfaces/ICapability";
import React from "react";
import { filterCapability } from "../funs/filterCapability";
import { CapabilityDropdown } from "../capability-dropdown";

export interface ICapabilityButtonProps<IData = any> extends ButtonProps {
    capability: ICapability;
    data?: IData;
    index?: number;
}

/** 功能组件-按钮 */
export function CapabilityButton<IData = any>(props: ICapabilityButtonProps<IData>) {

    const subMenu = React.useMemo(() => {
        if (props.capability.subMenu) {
            return filterCapability(props.capability.subMenu, props.data || {}, props.index);
        } else {
            return undefined
        }
    }, [props.capability.subMenu, props.data, props.index])

    const capability = React.useMemo(() => {
        if (props.capability) {
            return props.capability;
        } else if (subMenu?.length) {
            return subMenu[0];
        } else {
            return undefined
        }
    }, [props.capability, subMenu])

    if (subMenu) {
        return (
            <CapabilityDropdown capabilities={subMenu} data={props.data || {}} index={props.index} >
                <Button {...props} >{capability?.title}</Button>
            </CapabilityDropdown>
        )
    } else if (capability && capability.isEnable?.(props.data || {}, props.index || 0)) {
        return <MyButton {...props} capability={capability} />
    } else {
        return <></>
    }
}

function MyButton<IData = any>(props: ICapabilityButtonProps<IData>) {

    const { capability } = props;
    const { onClick, element, loading } = capability.useExpand?.(props.data || {}, props.index || 0) || {};
        
    return (
        <>
            {element}
            <Button
                {...props}
                disabled={props.disabled || capability.isDisabled?.(props.data || {}, props.index || 0)}
                onClick={onClick}
                loading={props.loading || !!loading}
            >
                {props.children || capability.title}
            </Button>
        </>
    )
}